<template>
    <n-upload action="" list-type="image-card" :custom-request="customRequest" @update:file-list="fileListUpdate">
    </n-upload>
</template>

<script lang="ts" setup>
import { upload } from '@/api/admin'
import { fileToBase64 } from '@/utils/common'
import { type UploadCustomRequestOptions, type UploadFileInfo } from 'naive-ui'

export type UploadFileResponse = UploadFileInfo & {
    response?: Api.Admin.UploadResponse
}

const emits = defineEmits<{
    updateList: [UploadFileResponse[]]
}>()

const map = new Map<string, Api.Admin.UploadResponse>()

async function customRequest({ file, onFinish, onError, onProgress }: UploadCustomRequestOptions) {
    const originFile = file.file
    if (!originFile) return
    const base64 = await fileToBase64(originFile)
    const [err, res] = await upload({ fileName: originFile.name, uriImageData: base64 })
    if (err) {
        onError()
    } else {
        map.set(file.id, res!)
        onFinish()
    }
}

function fileListUpdate(fileList: UploadFileInfo[]) {
    const fileListWithResponse = fileList.map(item => ({
        ...item,
        response: map.get(item.id)
    }))

    if (fileListWithResponse.find(item => !item.response)) return

    emits('updateList', fileListWithResponse)
}
</script>
